<template>
    <div class="app-container">
      <el-form :model="queryParams" class="frominfo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <div class="from-item">
          <el-form-item label="关键词" prop="keyword">
            <el-input v-model="queryParams.keyword" @keyup.enter.native="handleQuery" placeholder="请输入聊天内容" clearable/>
          </el-form-item>
          <el-form-item label="聊天时间" prop="begin">
            <el-date-picker v-model="chatTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="主体" prop="isMy">
            <el-select v-model="queryParams.isMy" placeholder="请选择" clearable>
              <el-option v-for="dict in arr" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </div>
        <div class="from-Btn">
          <el-form-item>
            <el-button class="blue-button" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
      <div style="background-color: #fff;padding-top: 10px;">
        <div class="ul-name"><div style="width:10%">客户</div><div style="width:10%">营销助手</div><div style="width:40%">聊天内容</div><div style="width:15%;">标签</div><div style="width:25%;">最近聊天时间</div></div>
        <ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto;font-size: 14px;">
          <li v-for="item,index in msgList" :key="index" class="li-box">
            <div style="width:10%">{{ item.isMy==0?item.sender:''}}</div>
            <div style="width:10%">{{ item.isMy==1?name!=''?name:item.sender:''}}</div>
            <div style="width:40%;padding: 8px 0;">{{ item.masg}}</div>
            <div style="width:15%">{{ item.lable}}</div>
            <div style="width:25%">{{ parseTime(item.createDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
          </li>
        </ul>
      </div>
        
      <div class="dialog">
          <div class="dia-ui"></div>
          <div class="dia-box">
              <div><svg-icon icon-class="xiaolian" @click="dialog" style="margin-right: 10px;"/><svg-icon icon-class="img" @click="uploadImg"/></div>
              <el-input type="textarea" :rows="5" v-model="content" placeholder="请输入文本，点击按钮/按回车发送"   @keydown.enter.native.prevent="enterEvent($event)"></el-input>
              <div class="dia-btn">
                <el-button style="width:80px;margin: 15px 15px 0 0;" @click="sendMsg" class="blue-button">发送</el-button>
              </div>
              <VEmojiPicker
                v-show="showDialog"
                :style="{ width: '50%', height: '100' }"
                labelSearch="Search"
                lang="pt-BR"
                @select="selectEmoji">
              </VEmojiPicker>
          </div>
          <div class="dia-ui"></div>
      </div>
    </div>
</template>
<script>
  var interval_timer=null
  var serverTimer =null
  import moment from "moment";
  import request from '@/utils/request'
  import { VEmojiPicker, emojisDefault, categoriesDefault } from 'v-emoji-picker'
  export default {
    name: "WcFriendInfo",
    dicts: ['sys_network_status'],
    components: {
      VEmojiPicker
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        showDialog:false,
        // 聊天记录
        msgList: [],
        total:0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          masqId: null,
          isGroup: 0,
          GroupId: null,
          isMy: null,
          sender: null,
          senderId: null,
          keyword: null,
          wcId: null,
          type: null,
          begin: null,
          end: null,
        },
        chatTime:[],
        arrId:[],
        arrMsg:[],
        addMsg:[],
        arr:[{label:'好友',value:0},{label:'助手',value:1}],
        content:"",
        webSocket:null,
        name:'',
        userName:'',
      };
    },
    created() {
      if(this.$store.state.user.roles.includes("admin")||this.$store.state.user.roles.includes("qxleader")||this.$store.state.user.roles.includes("sleader")){
        addZhushou({assistWcId:this.$route.query.wxid}).then(res=>{})
      }
      this.webSocket=new WebSocket(`${window.config.wsServerAddress}`+"?token="+this.$store.state.user.token)
      this.webSocket.onmessage=this.onmessage
      this.webSocket.onopen=this.onopen;
      //console.log(process.env.VUE_APP_SOCKET_API)
    },
    mounted(){
      //console.log(this.$route.query)
      this.queryParams.wcId = this.$route.query.wxid;
      this.queryParams.GroupId = this.$route.query.groupid;
      this.queryParams.senderId = this.$route.query.userid;
      this.userName=this.$route.query.username;
      this.name = this.$route.query.name;
      this.getList();
    },
    beforeDestroy(){
      if(this.$store.state.user.roles.includes("admin")||this.$store.state.user.roles.includes("qxleader")||this.$store.state.user.roles.includes("sleader")){
        demoveZhushou({assistWcId:this.queryParams.wcId}).then(res=>{})
      }
      clearInterval(interval_timer); 
      this.webSocket.close()
    },
    methods: {
      golink(){
        var wxid=this.$route.query.wxid 
        var groupid=this.$route.query.groupid
        this.$router.push({ path:"/group/notadd/",name:'notadd',query: {wxid,groupid,name:this.name}}).catch(()=>{});
      },
      dialog(){
        this.showDialog=!this.showDialog
      },
      uploadImg(){
            let input = document.createElement("input");
            input.type = "file";
            input.accept = "image/gif,image/jpeg,image/jpg,image/png";
            input.style.display = "none";
            input.addEventListener("change", function(e) {
              let formData = new FormData();
              let file = e.target.files[0];
              formData.append("imgfile", file); //传给后台的file的key值是可以自己定义的
              // formData.append("issueId", that.reply.issueId); //传给后台的file的key值是可以自己定义的
              // httpAction(that.url.addPicture,formData,"post").then((res)=>{
              //   console.log(res)
              //   if(res.success){
              //     that.$message.success("发送成功");
              //     that.$refs.chat.getReplyList(that.model.id)
              //   }else{
              //     that.$message.warning(res.message);
              //   }
              // }).finally(() => {
              //   that.confirmLoading = false;
              // })
            });
            document.body.appendChild(input);
            input.click();
      },
      /** 查询微信好友信息列表 */
      getList() {
        this.loading = true;
        listMsg(this.queryParams).then(res => {
          if (res['code']==200) {
            const dt = res['data'];
            this.total=dt['count'];
            this.msgList = [...this.msgList,...dt['documents']];
          }
          this.loading = false;
        });
        
      },
      enterEvent(event){
        console.log(event)
         //判断是否为enter+ctrl，如果不是回车键+ctrl取消默认换行行为，然后触发函数
         if(!event.ctrlKey){
           event.preventDefault();
           this.sendMsg();
         //如果是enter(回车键)+ctrl 则换行
         }else{
           this.content += '\n';
         }
      },
      selectEmoji(emoji) {
        this.content += emoji.data;
        //console.log(emoji)
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.loading=true
        this.msgList=[]
        this.queryParams.begin=null
        this.queryParams.end=null
        if(this.chatTime!=''&&this.chatTime!=null){
          this.queryParams.begin=this.chatTime[0]+' 00:00:00'
          this.queryParams.end=this.chatTime[1]+' 23:59:59'
        }
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.loading=true
        this.msgList=[]
        this.resetForm("queryForm");
        this.chatTime=[]
        this.handleQuery();
      },
      load(){
        // console.log(123)
        // console.log(this.total,this.queryParams.pageSize)
        if(this.total==this.queryParams.pageSize){
          this.queryParams.pageNum+=1
          this.getList()
        }
      },
      sendMsg(){
        if(this.content==null||this.content==''){
          this.$message({
            message: '请输入发送消息',
            type: 'warning'
          });
          return
        }
        var msg=this.content
        var msgId=this.getRandomString(8)
        var towx=this.queryParams.senderId
        if(this.queryParams.senderId==null||this.queryParams.senderId==''){
          towx=this.queryParams.GroupId
        }
        //console.log(msgId)
        var data={towx,msg,msgId}
        if(this.$store.state.user.roles.includes("admin")||this.$store.state.user.roles.includes("qxleader")||this.$store.state.user.roles.includes("sleader")){
          data={towx,msg,msgId,assistWcId:this.$route.query.wxid}
        }

        addMsg(data).then(res=>{
          this.arrId.unshift(msgId)
          this.arrMsg.unshift({masgId:msgId,isMy:1,sender:this.name,masg:msg,lable:'',createDate:moment().format('YYYY-MM-DD HH:mm:ss')})
          this.content=''
          this.$modal.msgSuccess("发送成功");
        })
      },

      getRandomString(length) {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        return Array.from({ length })
          .reduce((result) => result + characters.charAt(Math.floor(Math.random() * characters.length)), '');
      },
      onopen(){
        interval_timer=setInterval(this.heart,1000)   
      },
      heart(){
        try{
          this.webSocket.send("{'type':1}")
        }catch(error){
          //console.log('报错信息',error)
          clearInterval(interval_timer); 
          interval_timer=null
          this.webSocket.close();
          setTimeout(() => { 
              this.webSocket=new WebSocket(`${window.config.wsServerAddress}`+"?token="+this.$store.state.user.token)
              this.webSocket.onmessage=this.onmessage
              this.webSocket.onopen=this.onopen;
          },1000);
        }
      },
      onmessage(event){
          if(event.data.indexOf("msgId")!=-1){
             var data=JSON.parse(event.data)
             if(data.type==901){
              if(this.arrId.indexOf(data.msgId)!=-1){
                var index=this.arrId.indexOf(data.msgId)
                this.arrMsg[index].createDate=moment().format('YYYY-MM-DD HH:mm:ss')
                this.addMsg.push(this.arrMsg[index].masg+'_'+this.arrMsg[index].createDate)
                this.msgList.unshift(this.arrMsg[index])
              }
             }
          }
          if(event.data.indexOf("masgId")!=-1){
            var data=JSON.parse(event.data)
            if(data.isGroup=='0'){
              if(this.addMsg.indexOf(data.masg+'_'+data.createDate)==-1){
                this.msgList.unshift(data)
              }
            }
          }
      }

    }
  };
  
  /** js请求 调用 */
  //获取聊天记录
  export function listMsg(query) {
   return request({
     url: '/massage/get_mags',
     method: 'get',
     params: query
   })
  }
  //发送消息
  export function addMsg(query) {
   return request({
     url: '/msg/SetMsgTxt',
     method: 'post',
     data:query
   })
  }
  export function addZhushou(data) {
    return request({
      url: '/msg/AdminProxy',
      method: 'POST',
      data: data
    })
  }
  export function demoveZhushou(data) {
    return request({
      url: '/msg/AdminProxyCancel',
      method: 'POST',
      data: data
    })
  }
  </script>
<style lang="scss" scoped>
    .app-container{
      background-color: #f6f9fb;
      display: flex;
      flex-direction: column;
    }
    .linebtn{
        display: flex;
        margin: -10px 0 10px 5px;
        height: 40px;
        .btn{
            width: 100px;
            text-align: center;
            line-height: 40px;
            font-size: 14px;
            color: #8c8c8c;
            margin-right: 10px;
            border: 1px solid #eaeff2;
            background-color: #fff;
            border-radius: 5px;
            .link-type{
              color: #8c8c8c;
            }
        }
        .select{
            background-color: #eaf6ff;
            border:1px solid #288dfc;
            color: #288dfc;
            font-weight: 550;
        }
    }
    .frominfo{
      display: flex;background-color: #fff;padding: 10px;padding-bottom: 0; margin-bottom: 20px;
      .from-item{
        display: flex;flex-wrap: wrap;width: 80%;
      }
      .from-Btn{
        display: flex;flex-direction: column;align-items: center;justify-content: center;width: 20%;
      }
    }
    .mb8{
      margin-bottom: 20px;
    }
    .blue-button {
      color: #fff;
      background-color: #0078fb;
      border-color: #0078fb;
    }
    .dialog{
      background-color: #fff;
      padding: 20px;
      min-height: 240px;
      .dia-box{
        border: 1px solid #c9c6c6;
        border-radius: 10px;
        min-height: 200px;
        padding: 10px;
        display: flex;
        flex-direction: column;
        textarea{
          border: none;
          height: 70px;
          margin-top: 15px;
        }
        textarea:focus{
          outline: none;
        }
        .dia-btn{
          display: flex;
          flex-direction: row-reverse;
        }
      }
    }
    .infinite-list {
      height: 360px;
      padding: 0;
      margin: 0;
      list-style: none;
    }
    .infinite-list .infinite-list-item {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 50px;
      background: var(--el-color-primary-light-9);
      margin: 10px;
      color: var(--el-color-primary);
    }
    .infinite-list .infinite-list-item + .list-item {
      margin-top: 10px;
    }
    .ul-name{
      height: 35px;line-height: 35px;text-align: center;display: flex;border-bottom:1px solid #eee;font-size: 14px;font-weight: 600;
    }
    .li-box{
      word-break: break-all;
      overflow-wrap: break-word;
      min-height: 40px;display: flex;align-items: center;background-color: #fff;color: #8c8c8c;text-align: center;border-bottom:1px solid #eee;
    }
    ::v-deep .el-textarea__inner {
      border: none !important;
      box-shadow: none !important;
      font-size: 14px;
    }
</style>
  